package com.cloud.adrian.novel.config.wrapper;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.util.HashMap;
import java.util.Map;

/**
 * XSS 过滤处理
 * @Author: xiangguiliang
 * @version: 1.0
 * @since: 2024/06/04
 */

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private static final Map<String, String> REPLACE_RULE= new HashMap<>();

    static {
        REPLACE_RULE.put("<", "&lt;");
        REPLACE_RULE.put(">", "&gt;");
    }

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values != null) {
            int length = values.length;
            String[] escapedValues = new String[length];
            for (int i = 0; i < length; i++) {
                escapedValues[i] = values[i];
                int index = i;
                REPLACE_RULE.forEach(
                        (k, v) -> escapedValues[index] = escapedValues[index].replaceAll(k, v)
                );
            }
            return escapedValues;
        }
        return new String[0];
    }
}
